from tqdm import tqdm
from back_end.helpers import utils
from collections import defaultdict

def split_file_by_date(file):
    grouped_data = __get_grouped_data(utils.read_json(file))
    for date, items in tqdm(grouped_data.items(), desc='写入文件', unit='个'):
        utils.write_json(utils.get_path('RAW_DATA_PATH', date), items)

def __get_grouped_data(data):
    grouped_data = defaultdict(list)
    for item in data:
        grouped_data[__get_date(item.get('对话时间'))].append(item)
    return grouped_data

def __get_date(time):
    if not time:
        raise ValueError('No time data found in json item.')
    return __get_datetime(time.get('年'), time.get('月'), time.get('日'))

def __get_datetime(year, month, day):
    if not all([year, month, day]):
        raise ValueError('No year, month or day found in time data.')
    return f'{year}-{month}-{day}'
